/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Downloader;

import CrlException.CrlException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

/**
 *
 * @author CUHUUHOANG
 */
public class ImageDownloader {

    public String DownloadImage(String url, String path) throws CrlException {
        InputStream in = null;
        try {
            URL myUrl = new URL(url);
            ByteArrayOutputStream out;
            in = new BufferedInputStream(myUrl.openStream());
            out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int n = 0;
            while (-1 != (n = in.read(buf))) {
                out.write(buf, 0, n);
            }
            out.close();
            byte[] response = out.toByteArray();
            String outputPath=path + "/" + getImageName(url,path);
            FileOutputStream fos = new FileOutputStream(outputPath);
            fos.write(response);
            fos.close();
            return outputPath;
        } catch (Exception ex) {
            throw new CrlException(ex.getMessage());
        } finally {
            try {
                in.close();
            } catch (Exception ex) {
                throw new CrlException(ex.getMessage());
            }
        }
    }

    public String getImageName(String url, String path) throws CrlException {
        try {
            String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
            String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
            String extn = fileName.substring(fileName.lastIndexOf('.')+1);

            int num = 0;
            String imageName = fileName;
            File f = new File(path + '/' + imageName);
            while (f.exists()) {
                num++;
                imageName = fileNameWithoutExtn + "(" + num + ")." + extn;
                f = new File(path + '/' + imageName);
            }
            return imageName;
        } catch (Exception ex) {
            throw new CrlException(ex.getMessage());
        }

    }
}
